﻿using DFGK.WMS.Common.Attributes;
using DFGK.WMS.Common.Result;
using DFGK_WMS.Model.DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;
using System.Reflection;

namespace DFGJ.WMS_PDA.WebAPI.Utility.Filters
{
    /// <summary>
    /// 幂等验证Filter
    /// </summary>
    public class IdempotentFilterAttribute : Attribute, IAsyncActionFilter
    {
        private readonly IMemoryCache _MemoryCache;
        public IdempotentFilterAttribute(IMemoryCache memoryCache)
        {
            _MemoryCache = memoryCache;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {

            //唯一标识   
            object? idempotemtObj = context.ActionArguments.Where(it => it.Value is IdempotentDto).Select(x => x.Value).FirstOrDefault();
            if (idempotemtObj != null)
            {
                object? _MemoryKey = null;

                foreach (var item in idempotemtObj.GetType().GetProperties())
                {
                    if (item.IsDefined(typeof(IdempotentAttribute), true))
                    {
                        //IdempotentFilterAttribute idempotent = item.GetCustomAttribute<IdempotentFilterAttribute>();
                        _MemoryKey = item.GetValue(idempotemtObj);

                    }

                }

                if (_MemoryKey == null || _MemoryKey == "")
                {
                    //context.Result = new JsonResult(new ApiBaseResult { Success = false, Message = "幂等Key不能为空" });
                    await next.Invoke();
                }
                else
                {
                    string? key = _MemoryCache.Get<string>(_MemoryKey!);
                    if (key == null)
                    {
                        _MemoryCache.Set(_MemoryKey!, string.Empty, TimeSpan.FromSeconds(2));
                        await next.Invoke();
                    }
                    else
                    {
                        context.Result = new JsonResult(new ApiBaseResult { Success = false, Message = "系统繁忙", Code = "116" });
                    }
                }
            }
            else
            {
                await next.Invoke();
            }


        }
    }
}
